package com.longdaji.decoration.ui.activitiesOfMine.personData;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.longdaji.decoration.Constants;
import com.longdaji.decoration.R;
import com.longdaji.decoration.base.BaseActivity;
import com.longdaji.decoration.bean.Account;
import com.longdaji.decoration.ui.CameraActivity;
import com.longdaji.decoration.ui.activitiesOfMine.personData.changeDormitory.ChangeDormitoryActivity;
import com.longdaji.decoration.ui.activitiesOfMine.personData.changeLabel.ChangeLabelActivity;
import com.longdaji.decoration.ui.activitiesOfMine.personData.changeName.ChangeNameActivity;
import com.longdaji.decoration.ui.activitiesOfMine.personData.changeSignature.ChangeSignatureActivity;
import com.longdaji.decoration.ui.activitiesOfMine.personData.changeUsername.ChangeUsernameActivity;
import com.longdaji.decoration.ui.login.passwordLogin.PasswordLoginActivity;
import com.longdaji.decoration.utils.AddressPickerDialog;
import com.longdaji.decoration.utils.BottomDialog;
import com.longdaji.decoration.utils.ConstellationDialog;
import com.longdaji.decoration.utils.LogUtil;
import com.longdaji.decoration.utils.PortraitAddressUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.AddressProvider;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;
import io.reactivex.functions.Consumer;

public class PersonalDataActivity extends BaseActivity implements PersonalDataContract.View, OnAddressSelectedListener, AddressProvider {

    private static final int REQUEST_CODE_CHOOSE = 23;
    private Bundle bundle;
    private String username;
    private String telephone;
    private String password;
    private int isGraduate = 0;
    private boolean isRegister = false;

    private ProgressDialog pd;


    @Inject
    PersonalDataContract.Presenter mPresenter;

    @BindView(R.id.tv_tool_title)
    TextView tvTitle;
    @BindView(R.id.iv_head_portrait)
    ImageView ivHeadPortrait;
    private List<Uri> mUriList = new ArrayList<>();
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_gender)
    TextView tvGender;
    @BindView(R.id.tv_constellation)
    TextView tvConstellation;
    @BindView(R.id.tv_signature)
    TextView tvSignature;
    @BindView(R.id.tv_label)
    TextView tvLabel;
    @BindView(R.id.tv_campus)
    TextView tvCampus;
    @BindView(R.id.rl_change_campus)
    RelativeLayout rlChangeCampus;
    @BindView(R.id.tv_dormitory)
    TextView tvDormitory;

    private Account account;
    private AddressPickerDialog mCampusPickerDialog;
    private String headPortraitUri;
    private ConstellationDialog mConstellationDialog;
    private String qiNiuToken;
    private SimpleDateFormat formatter;
    private boolean isHeadChanged = false;

    //相机
    private final int GET_PERMISSION_REQUEST = 100; //权限申请自定义码


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_data);
        setUnBinder(ButterKnife.bind(this));
        if (mPresenter != null)
            mPresenter.setView(this);
        tvTitle.setText("个人资料");
        mPresenter.initPresenter();

        initView();

    }

    private void initView() {
        account = Account.getInstance();
        tvUsername.setText(account.getUsername());
        tvName.setText(account.getName());
        tvGender.setText(account.getGender());
        tvConstellation.setText(account.getConstellation());
        //??DefFlag
        tvSignature.setText(account.getSign());
        tvLabel.setText(account.getRemark());
        tvCampus.setText(account.getCampusName());
        tvDormitory.setText(account.getDormitoryName());
        Glide.with(this).load(account.getHeadImgLocation()).into(ivHeadPortrait);
        //initPicker
        mCampusPickerDialog = new AddressPickerDialog(this);
        // TODO: 2018/3/17 0017 获取列表
        mCampusPickerDialog.selector.setAddressProvider(this);
        mCampusPickerDialog.selector.setOnAddressSelectedListener(this);

        getBundleData();

        if (isRegister && isGraduate == 1 || !isRegister && account.getIsGraduate() == 1) {
            rlChangeCampus.setVisibility(View.GONE);
        }

        formatter = new SimpleDateFormat("yyyyMMddHHmmss");


    }

    private void getBundleData() {
        bundle = getIntent().getExtras();
        if (bundle != null) {
            LogUtil.d("graduatetest", "isGraduate: " + isGraduate);
            telephone = bundle.getString("telephone");
            password = bundle.getString("password");
            isGraduate = bundle.getInt("isGraduate");
            isRegister = bundle.getBoolean("isRegister");

        }


    }

    // TODO: 2018/3/28 0028 只需要在注册时候传入0和1，后面修改就都可以设置为男和女
    private String formatGender(String gender) {
        if (TextUtils.equals("男", gender)) {
            return "0";
        } else if (TextUtils.equals("女", gender)) {
            return "1";
        } else {
            Log.e("PersonalDataActivity", "gender error");
            return null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null)
            mPresenter.detachView();
    }

    @OnClick({R.id.rl_tool_back, R.id.tv_finish, R.id.rl_change_head_portrait, R.id.rl_change_username, R.id.rl_change_name, R.id.rl_change_gender,
            R.id.rl_change_constellation, R.id.rl_change_signature, R.id.rl_change_label, R.id.rl_change_campus, R.id.rl_change_dormitory
    })
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_tool_back:
                finish();
                break;
            case R.id.tv_finish:
                showProgressDialog();
                if (isRegister) {
                    mPresenter.OnRegisterPersonalData(isHeadChanged, tvUsername.getText().toString(), tvName.getText().toString(), telephone, password,
                            tvLabel.getText().toString(), tvSignature.getText().toString(), tvConstellation.getText().toString(), formatGender(tvGender.getText().toString()),
                            headPortraitUri, null, tvCampus.getText().toString(), tvDormitory.getText().toString(), isGraduate);
                } else {
                    mPresenter.onUpdateData(isHeadChanged, account.getUserid(), tvUsername.getText().toString(), tvName.getText().toString(),
                            tvConstellation.getText().toString(), formatGender(tvGender.getText().toString()), headPortraitUri, null, tvLabel.getText().toString(), tvSignature.getText().toString(),
                            tvCampus.getText().toString(), account.getCredits(), tvDormitory.getText().toString());
                }

                break;
            case R.id.rl_change_head_portrait:
                final BottomDialog headPortraitBottomDialog = new BottomDialog(this, "拍照", "从手机相册选择");
                headPortraitBottomDialog.setBottomDialogListener(new BottomDialog.BottomDialogListener() {
                    @Override
                    public void onItemOneClick() {
                        getPermissions();
                    }

                    @Override
                    public void onItemTwoClick() {
//                        headPortraitBottomDialog.dismiss();
                        RxPermissions rxPermissions = new RxPermissions(PersonalDataActivity.this);
                        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(Boolean aBoolean) throws Exception {
                                        if (aBoolean) {
                                            Log.d("mytest", "add photo");
                                            Matisse.from(PersonalDataActivity.this)
                                                    .choose(MimeType.allOf())
                                                    .countable(false)
//                                                    .capture(true)
//                                                    .captureStrategy(
//                                                            new CaptureStrategy(true, "com.longdaji.decoration.fileprovider"))
                                                    .theme(R.style.Matisse_Dracula)
                                                    .maxSelectable(1)
                                                    .imageEngine(new GlideEngine())
                                                    .forResult(REQUEST_CODE_CHOOSE);
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onItemThreeClick() {

                    }
                });
                headPortraitBottomDialog.show();
                break;
            case R.id.rl_change_username:
                Intent intentChangeUsername = new Intent(this, ChangeUsernameActivity.class);
                startActivityForResult(intentChangeUsername, Constants.REQUEST_CODE_CHANGE_USERNAME);
                break;
            case R.id.rl_change_name:
                Intent intentChangeName = new Intent(this, ChangeNameActivity.class);
                startActivityForResult(intentChangeName, Constants.REQUEST_CODE_CHANGE_NAME);
                break;
            case R.id.rl_change_gender:
                final BottomDialog genderBottomDialog = new BottomDialog(this, "男", "女");
                genderBottomDialog.setBottomDialogListener(new BottomDialog.BottomDialogListener() {
                    @Override
                    public void onItemOneClick() {
                        mPresenter.onMaleChosen();
//                        genderBottomDialog.dismiss();
                    }

                    @Override
                    public void onItemTwoClick() {
//                        genderBottomDialog.dismiss();
                        mPresenter.onFemaleChosen();

                    }

                    @Override
                    public void onItemThreeClick() {

                    }
                });
                genderBottomDialog.show();
                break;
            case R.id.rl_change_constellation:

                createConstellationDialog();
                break;
            case R.id.rl_change_signature:
                Intent intentChangeSignature = new Intent(this, ChangeSignatureActivity.class);
                startActivityForResult(intentChangeSignature, Constants.REQUEST_CODE_CHANGE_SIGNATURE);
                break;
            case R.id.rl_change_label:
                Intent intentChangeLabel = new Intent(this, ChangeLabelActivity.class);
                startActivityForResult(intentChangeLabel, Constants.REQUEST_CODE_CHANGE_LABEL);
                break;
            case R.id.rl_change_campus:
                mCampusPickerDialog.show();
                break;
            case R.id.rl_change_dormitory:
                Intent intentChangeDormitory = new Intent(this, ChangeDormitoryActivity.class);
                startActivityForResult(intentChangeDormitory, Constants.REQUEST_CODE_CHANGE_DORMITORY);
                break;
            default:
                break;
        }
    }

    private void showProgressDialog() {
        if (pd == null) {
            pd = new ProgressDialog(this);
            pd.setMessage("加载中...");
            pd.setCanceledOnTouchOutside(false);
        }
        if (!pd.isShowing()) {
            pd.show();
        }
    }

    private void hideProgressDialog() {
        if (pd != null && pd.isShowing())
            pd.dismiss();
    }

    /**
     * 获取权限
     */
    private void getPermissions() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager
                    .PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager
                            .PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager
                            .PERMISSION_GRANTED) {
                startActivityForResult(new Intent(PersonalDataActivity.this, CameraActivity.class), Constants.REQUEST_CODE_CAPTURE);
            } else {
                //不具有获取权限，需要进行权限申请
                ActivityCompat.requestPermissions(PersonalDataActivity.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA}, GET_PERMISSION_REQUEST);
            }
        } else {
            startActivityForResult(new Intent(PersonalDataActivity.this, CameraActivity.class), Constants.REQUEST_CODE_CAPTURE);
        }
    }

    private void createConstellationDialog() {
        if (mConstellationDialog == null) {
            mConstellationDialog = new ConstellationDialog(PersonalDataActivity.this);
            mConstellationDialog.setConstellationListener(new ConstellationDialog.ConstellationListener() {
                @Override
                public void onConstellationClick(String cons) {
                    tvConstellation.setText(cons);
                }
            });
        }
        if (!mConstellationDialog.isShowing())
            mConstellationDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mUriList = Matisse.obtainResult(data);
            LogUtil.d("mytest", "mUriList: " + mUriList);
            headPortraitUri = PortraitAddressUtil.getRealPathFromUri(this, mUriList.get(0));
            isHeadChanged = true;
            Glide.with(this).load(mUriList.get(0)).into(ivHeadPortrait);
//            mPresenter.changeHeadPortraitByAlbum(PortraitAddressUtil.getRealPathFromUri(this, mUriList.get(0)), formatter.format(new Date(System.currentTimeMillis())), qiNiuToken);
        } else if (requestCode == Constants.REQUEST_CODE_CHANGE_SIGNATURE && resultCode == Constants.RESULT_CODE_CHANGE_SIGNATURE) {
            tvSignature.setText(data.getStringExtra("signature"));
        } else if (requestCode == Constants.REQUEST_CODE_CHANGE_LABEL && resultCode == Constants.RESULT_CODE_CHANGE_LABEL) {
            tvLabel.setText(data.getStringExtra("label"));
        } else if (requestCode == Constants.REQUEST_CODE_CHANGE_NAME && resultCode == Constants.RESULT_CODE_CHANGE_NAME) {
            tvName.setText(data.getStringExtra("name"));
        } else if (requestCode == Constants.REQUEST_CODE_CHANGE_USERNAME && resultCode == Constants.RESULT_CODE_CHANGE_USERNAME) {
            Log.d("tmpTest", "username : " + data.getStringExtra("username"));
            tvUsername.setText(data.getStringExtra("username"));
        } else if (requestCode == Constants.REQUEST_CODE_CHANGE_DORMITORY && resultCode == Constants.RESULT_CODE_CHANGE_DORMITORY) {
            tvDormitory.setText(data.getStringExtra("dormitory"));
        } else if (resultCode == 101) {
            String path = data.getStringExtra("path");
            Log.d("mytest", "path: " + path);
            headPortraitUri = path;
            isHeadChanged = true;
            Glide.with(this).load(path).into(ivHeadPortrait);
        } else if (resultCode == 103) {
            Toast.makeText(this, "请检查相机权限~", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showHeadPortraitChanged() {
        Glide.with(this).load(headPortraitUri).into(ivHeadPortrait);
    }

    @Override
    public void showMaleChosen() {
        tvGender.setText("男");
    }

    @Override
    public void showFemaleChosen() {
        tvGender.setText("女");
    }

    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        mCampusPickerDialog.dismiss();
        if (county != null)
            tvCampus.setText(county.name);
    }

    @Override
    public void provideProvinces(AddressReceiver<Province> addressReceiver) {
//        addressReceiver.send(mMyProvinces);
        addressReceiver.send(mPresenter.getProvince());
    }

    @Override
    public void provideCitiesWith(int provinceId, AddressReceiver<City> addressReceiver) {
        List<City> cityList = new ArrayList<>();
        for (City city : mPresenter.getCity()) {
            if (city.province_id == provinceId) {
                cityList.add(city);
            }
        }
        addressReceiver.send(cityList);
    }

    @Override
    public void provideCountiesWith(int cityId, AddressReceiver<County> addressReceiver) {
        List<County> countyList = new ArrayList<>();
        for (County county : mPresenter.getCampus()) {
            if (county.city_id == cityId) {
                countyList.add(county);
            }
        }
        addressReceiver.send(countyList);
    }

    @Override
    public void provideStreetsWith(int countyId, AddressReceiver<Street> addressReceiver) {
        addressReceiver.send(null);
    }

    @Override
    public void showUpdateSucceed(boolean isUserInfo) {
        updateAccountData(isUserInfo);
        hideProgressDialog();
        finish();
    }

    private void updateAccountData(boolean isUserInfo) {
        Log.d("tmpTest", "updateAccountData" + isUserInfo);
        if (isUserInfo) {
            account.setUsername(tvUsername.getText().toString());
            account.setName(tvName.getText().toString());
            account.setGender(tvGender.getText().toString());
            account.setConstellation(tvConstellation.getText().toString());
            account.setSign(tvSignature.getText().toString());
            account.setRemark(tvLabel.getText().toString());
            if (headPortraitUri != null) {
                account.setHeadImgLocation(headPortraitUri);
            }
        } else {
            account.setCampusName(tvCampus.getText().toString());
            account.setDormitoryName(tvDormitory.getText().toString());
        }
    }

    @Override
    public void showRegisterDefect(int defectNo) {
        switch (defectNo) {
            case 0:
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                break;
            case 1:
                Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
                break;
//            case 2:
//                Toast.makeText(this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
//                break;
//            case 3:
//                Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
//                break;
//            case 4:
//                Toast.makeText(this, "毕业状态不能为空", Toast.LENGTH_SHORT).show();
//                break;
            default:
                break;
        }
    }

    @Override
    public void showRegisterSucceed() {
        Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, PasswordLoginActivity.class);
        intent.putExtra(Constants.REGISTER_USERNAME, tvUsername.getText().toString());
        intent.putExtra(Constants.REGISTER_PASSWORD, password);
        PasswordLoginActivity.start(PersonalDataActivity.this, intent);
        hideProgressDialog();
        finish();
    }

    @Override
    public void showUsernameVerifyFailed() {
        Toast.makeText(this, "用户名已被使用", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showQiNiuToken(String token) {
        qiNiuToken = token;
    }

    @Override
    public void showUpLoadResult(boolean isSuccess, String url) {
        LogUtil.d("uploadtest", "showUpLoadResult: " + isSuccess + "----" + url);
        if (isSuccess) {
            headPortraitUri = url;
            Toast.makeText(this, "头像上传成功", Toast.LENGTH_SHORT).show();
        } else
            Toast.makeText(this, "头像上传失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showRegisterError() {
        hideProgressDialog();
    }
}
